define(["jquery", "bootstrap", "backend", "table", "form"], function (
  $,
  undefined,
  Backend,
  Table,
  Form
) {
  /**
   * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
   */
  class OrderStatus {
    static PENDING_PAYMENT = 1;
    static TO_BE_CONFIRMED = 2;
    static CONFIRMED = 3;
    static DELIVERY_IN_PROGRESS = 4;
    static COMPLETED = 5;
    static CANCELLED = 6;
  }

  var Controller = {
    index: function () {
      // 初始化表格参数配置
      Table.api.init({
        extend: {
          index_url: "orders/index" + location.search,
          add_url: "orders/add",
          edit_url: "orders/edit",
          del_url: "orders/del",
          multi_url: "orders/multi",
          import_url: "orders/import",
          table: "orders",
        },
      });

      var table = $("#table");
      var status = localStorage.getItem("status");
      console.log("status:", status);

      // 初始化表格
      table.bootstrapTable({
        url: $.fn.bootstrapTable.defaults.extend.index_url,
        pk: "id",
        sortName: "id",
        fixedColumns: true,
        fixedRightNumber: 1,
        commonSearch: true,
        search: false,
        searchFormVisible: true,
        showToggle: false,
        showColumns: false,
        showExport: false,
        queryParams: function (params) {
          params.type = status;
          return params;
        },
        columns: [
          [
            { field: "number", title: __("Number"), operate: "LIKE" },
            {
              field: "phone",
              title: __("Phone"),
              operate: "LIKE",
              visible: false,
            },
            {
              field: "order_time",
              title: __("Order_time"),
              operate: "RANGE",
              addclass: "datetimerange",
              autocomplete: false,
            },
            {
              field: "order_dish",
              title: __("Order_dish"),
              table: table,
              class: "autocontent",
              formatter: Table.api.formatter.content,
              operate: false,
            },
            {
              field: "address",
              title: __("Address"),
              table: table,
              class: "autocontent",
              formatter: Table.api.formatter.content,
              operate: false,
            },
            {
              field: "estimated_delivery_time",
              title: __("estimatedDeliveryTime"),
              operate: "RANGE",
              addclass: "datetimerange",
              autocomplete: false,
              operate: false,
            },
            {
              field: "remark",
              title: __("Remark"),
              table: table,
              class: "autocontent",
              formatter: Table.api.formatter.content,
              operate: false,
            },
            {
              field: "tableware_number",
              title: __("tablewareNumber"),
              operate: false,
            },
            {
              field: "status",
              title: __("Status"),
              operate: false,
              visible: false,
              searchList: {
                1: __("Status 1"),
                2: __("Status 2"),
                3: __("Status 3"),
                4: __("Status 4"),
                5: __("Status 5"),
                6: __("Status 6"),
                7: __("Status 7"),
              },
              formatter: Table.api.formatter.status,
            },

            {
              field: "buttons",
              width: "120px",
              title: __("操作"),
              table: table,
              events: Table.api.events.operate,
              operate: false,
              buttons: [
                {
                  name: "jiedna",
                  text: __("接单"),
                  title: __("接单"),
                  classname: "btn btn-xs btn-success btn-magic btn-ajax",
                  icon: "fa fa-magic",
                  url: "ajax/acceptOrder",
                  confirm: "确定接单",
                  success: function (data, ret) {
                    // Layer.alert(ret.msg + ",返回数据：" + JSON.stringify(data));
                    //如果需要阻止成功提示，则必须使用return false;
                    table.bootstrapTable("refresh"); // 刷新表格
                    return false;
                  },
                  error: function (data, ret) {
                    console.log(data, ret);
                    Layer.alert(ret.msg);
                    return false;
                  },
                  visible: function (row) {
                    //返回true时按钮显示,返回false隐藏
                    return [2].includes(row.status);
                  },
                },
                {
                  name: "paisong",
                  text: __("派送"),
                  title: __("派送"),
                  classname: "btn btn-xs btn-success btn-magic btn-ajax",
                  icon: "fa fa-magic",
                  url: "ajax/deliveryOrder",
                  confirm: "确定派送",
                  success: function (data, ret) {
                    // Layer.alert(ret.msg + ",返回数据：" + JSON.stringify(data));
                    //如果需要阻止成功提示，则必须使用return false;
                    table.bootstrapTable("refresh"); // 刷新表格
                    return false;
                  },
                  error: function (data, ret) {
                    console.log(data, ret);
                    Layer.alert(ret.msg);
                    return false;
                  },
                  visible: function (row) {
                    //返回true时按钮显示,返回false隐藏
                    return [3].includes(row.status);
                  },
                },
                {
                  name: "wancheng",
                  text: __("完成"),
                  title: __("完成"),
                  classname: "btn btn-xs btn-success btn-magic btn-ajax",
                  icon: "fa fa-magic",
                  url: "ajax/compOrder",
                  confirm: "确认完成",
                  success: function (data, ret) {
                    // Layer.alert(ret.msg + ",返回数据：" + JSON.stringify(data));
                    //如果需要阻止成功提示，则必须使用return false;
                    table.bootstrapTable("refresh"); // 刷新表格
                    return false;
                  },
                  error: function (data, ret) {
                    console.log(data, ret);
                    Layer.alert(ret.msg);
                    return false;
                  },
                  visible: function (row) {
                    //返回true时按钮显示,返回false隐藏
                    return [4].includes(row.status);
                  },
                },
                {
                  name: "tuidan",
                  text: __("退单"),
                  title: __("退单"),
                  classname: "btn btn-xs btn-success btn-magic btn-ajax",
                  icon: "fa fa-magic",
                  url: "ajax/returnOrder",
                  success: function (data, ret) {
                    // Layer.alert(ret.msg + ",返回数据：" + JSON.stringify(data));
                    //如果需要阻止成功提示，则必须使用return false;
                    table.bootstrapTable("refresh"); // 刷新表格
                    return false;
                  },
                  error: function (data, ret) {
                    console.log(data, ret);
                    Layer.alert(ret.msg);
                    return false;
                  },
                  visible: function (row) {
                    //返回true时按钮显示,返回false隐藏
                    return [5].includes(row.status);
                  },
                },
                {
                  name: "cancel",
                  text: __("取消"),
                  title: __("取消原因"),
                  classname: "btn btn-xs btn-success btn-magic btn-ajax",
                  classname: "btn btn-xs btn-primary btn-dialog",
                  icon: "fa fa-list",
                  url: "orders/cancel",
                  callback: function (data) {
                    // Layer.alert("接收到回传数据：" + JSON.stringify(data), {
                    //   title: "回传数据",
                    // });
                  },
                  visible: function (row) {
                    //返回true时按钮显示,返回false隐藏
                    return [1, 3, 4].includes(row.status);
                  },
                },
                {
                  name: "detail",
                  text: __("查看"),
                  title: __("订单信息"),
                  classname: "btn btn-xs btn-success btn-magic btn-ajax",
                  classname: "btn btn-xs btn-primary btn-dialog",
                  icon: "fa fa-list",
                  url: "orders/detail",
                  callback: function (data) {
                    Layer.alert("接收到回传数据：" + JSON.stringify(data), {
                      title: "回传数据",
                    });
                  },
                  visible: function (row) {
                    //返回true时按钮显示,返回false隐藏
                    return true;
                  },
                },
              ],
              formatter: Table.api.formatter.buttons,
            },
            // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
          ],
        ],
      });

      // 为表格绑定事件
      Table.api.bindevent(table);

      if (status) {
        $(
          ".nav-tabs > li > a[data-value='" +
            localStorage.getItem("status") +
            "']"
        ).trigger("click");
        localStorage.removeItem("status");
      }

      var orderId = localStorage.getItem("orderId");
      console.log("orderId", orderId);

      if (orderId) {
        Fast.api.open("orders/detail/ids/" + orderId, "订单信息");
        localStorage.removeItem("orderId");
      }

      //绑定TAB事件
      $('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
        // var options = table.bootstrapTable(tableOptions);
        var typeStr = $(this).attr("href").replace("#", "");
        var options = table.bootstrapTable("getOptions");
        options.pageNumber = 1;
        options.queryParams = function (params) {
          // params.filter = JSON.stringify({type: typeStr});
          params.type = typeStr;

          return params;
        };
        table.bootstrapTable("refresh", {});
        return false;
      });

      // 页面加载后启动定时刷新（每 10 秒刷新一次）
      // var refreshTimer = setInterval(function () {
      //   table.bootstrapTable("refresh");
      // }, 10000); // 10秒 = 10000ms

      var fetchAndUpdateCountTimer;

      // 页面加载完成后初始化
      $(function () {
        // 1. 初始加载一次（避免页面首次渲染无数据）
        fetchAndUpdateCounts();

        // 2. 每 3 秒轮询一次（间隔可根据需求调整，建议 ≥2 秒）
        fetchAndUpdateCountTimer = setInterval(fetchAndUpdateCounts, 3000);
      });

      // // 页面关闭时清除定时器（避免内存泄漏）
      $(window).on("beforeunload", function () {
        // clearInterval(refreshTimer);
        clearInterval(fetchAndUpdateCountTimer);
      });

      /**
       * 轮询接口 → 获取最新计数 → 更新 badge
       */
      function fetchAndUpdateCounts() {
        $.ajax({
          url: "ajax/getStatusCounts", // 后端接口地址
          type: "GET",
          dataType: "json",
          success: function (res) {
            if (res.code !== 1) return; // 接口失败则跳过
            refreshCount();
            // 遍历所有带 data-status 的 li 元素
            $("li[data-status]").each(function () {
              const $li = $(this);
              const status = $li.data("status"); // 获取当前 li 对应的状态
              if (
                status == OrderStatus.COMPLETED ||
                status == OrderStatus.CANCELLED
              ) {
                return;
              }
              // 在接口返回的数据中找到对应状态的计数
              const targetCount = res.data.find(
                (item) => item.status == status
              );

              if (targetCount) {
                // 定位 li 下的 badge 元素，更新文本
                if (targetCount.count > 99) {
                  $li.find(".badge").text("99+");
                } else {
                  $li.find(".badge").text(targetCount.count);
                }

                // 可选：添加动画效果（需 Bootstrap 动画 CSS）
                // $li
                //   .find(".badge")
                //   .addClass("animated pulse") // 闪烁动画
                //   .one("animationend", function () {
                //     $(this).removeClass("animated pulse");
                //   });
              }
            });
          },
          error: function () {
            console.error("获取订单计数失败");
          },
        });
      }

      // 刷新数量
      function refreshCount() {
        $("li[data-status]").each(function () {
          const $li = $(this);
          const status = $li.data("status"); // 获取当前 li 对应的状态
          if (
            status == OrderStatus.COMPLETED ||
            status == OrderStatus.CANCELLED
          ) {
            return;
          }

          // 定位 li 下的 badge 元素，更新文本
          $li.find(".badge").text("");
        });
      }
    },
    add: function () {
      Controller.api.bindevent();
    },
    edit: function () {
      Controller.api.bindevent();
    },
    detail: function () {
      var fanhui = $("#fanhui");
      if (fanhui) {
        fanhui.click(function (e) {
          e.preventDefault();
          console.log("点击返回按钮");
          var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
          parent.Layer.close(index); //再执行关闭
        });
      }

      var acceptOrderBtn = $("#acceptOrderBtn");
      if (acceptOrderBtn) {
        acceptOrderBtn.click(function (e) {
          e.preventDefault();
          $.post(
            "ajax/acceptOrder/ids/" + $("#orderId").val(),
            {},
            function (data, textStatus, jqXHR) {
              console.log(data);
              if (data.code == 0) {
                Layer.msg(data.msg, { icon: 2 });
              } else {
                Layer.msg(data.msg, { icon: 1 });
                setTimeout(() => {
                  var index = parent.Layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                  parent.Layer.close(index); //再执行关闭
                }, 500);
              }
            },
            "json"
          );
        });
      }

      var paiSongBtn = $("#paiSongBtn");
      if (paiSongBtn) {
        paiSongBtn.click(function (e) {
          e.preventDefault();
          $.post(
            "ajax/deliveryOrder/ids/" + $("#orderId").val(),
            {},
            function (data, textStatus, jqXHR) {
              console.log(data);
              if (data.code == 0) {
                Layer.msg(data.msg, { icon: 2 });
              } else {
                Layer.msg(data.msg, { icon: 1 });
                setTimeout(() => {
                  var index = parent.Layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                  parent.Layer.close(index); //再执行关闭
                }, 500);
              }
            },
            "json"
          );
        });
      }

      var wanChengBtn = $("#wanChengBtn");
      if (wanChengBtn) {
        wanChengBtn.click(function (e) {
          e.preventDefault();
          $.post(
            "ajax/compOrder/ids/" + $("#orderId").val(),
            {},
            function (data, textStatus, jqXHR) {
              console.log(data);
              if (data.code == 0) {
                Layer.msg(data.msg, { icon: 2 });
              } else {
                Layer.msg(data.msg, { icon: 1 });
                setTimeout(() => {
                  var index = parent.Layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                  parent.Layer.close(index); //再执行关闭
                }, 500);
              }
            },
            "json"
          );
        });
      }

      var tuiDanBtn = $("#tuiDanBtn");
      if (tuiDanBtn) {
        tuiDanBtn.click(function (e) {
          e.preventDefault();
          $.post(
            "ajax/returnOrder/ids/" + $("#orderId").val(),
            {},
            function (data, textStatus, jqXHR) {
              console.log(data);
              if (data.code == 0) {
                Layer.msg(data.msg, { icon: 2 });
              } else {
                Layer.msg(data.msg, { icon: 1 });
                setTimeout(() => {
                  var index = parent.Layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                  parent.Layer.close(index); //再执行关闭
                }, 500);
              }
            },
            "json"
          );
        });
      }

      var cancelModal = $("#cancelModal");
      if (cancelModal) {
        $("#readyBtn").click(function (e) {
          e.preventDefault();
          cancelModal.modal("hide");
        });

        cancelModal.on("hide.bs.modal", function (e) {
          // console.log($("#cancelReason").val());
          $.post(
            "ajax/cancelOrder/ids/" + $("#orderId").val(),
            {
              cancelReason: $("#cancelReason").val(),
            },
            function (data, textStatus, jqXHR) {
              console.log(data);
              if (data.code == 0) {
                Layer.msg(data.msg, { icon: 2 });
              } else {
                Layer.msg(data.msg, { icon: 1 });
                setTimeout(() => {
                  var index = parent.Layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                  parent.Layer.close(index); //再执行关闭
                }, 500);
              }
            },
            "json"
          );
        });
      }

      var rejectionModal = $("#rejectionModal");
      if (rejectionModal) {
        $("#readyBtn").click(function (e) {
          e.preventDefault();
          rejectionModal.modal("hide");
        });

        rejectionModal.on("hide.bs.modal", function (e) {
          // console.log($("#cancelReason").val());
          $.post(
            "ajax/rejectionOrder/ids/" + $("#orderId").val(),
            {
              rejectionReason: $("#rejectionReason").val(),
            },
            function (data, textStatus, jqXHR) {
              console.log(data);
              if (data.code == 0) {
                Layer.msg(data.msg, { icon: 2 });
              } else {
                Layer.msg(data.msg, { icon: 1 });
                setTimeout(() => {
                  var index = parent.Layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                  parent.Layer.close(index); //再执行关闭
                }, 500);
              }
            },
            "json"
          );
        });
      }
    },
    cancel: function () {
      $("#readyBtn").click(function (e) {
        e.preventDefault();
        $.post(
          "ajax/cancelOrder/ids/" + $("#orderId").val(),
          {
            cancelReason: $("#cancelReason").val(),
          },
          function (data, textStatus, jqXHR) {
            console.log(data);
            if (data.code == 0) {
              Layer.msg(data.msg, { icon: 2 });
            } else {
              Layer.msg(data.msg, { icon: 1 });
              setTimeout(() => {
                var index = parent.Layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                parent.Layer.close(index); //再执行关闭
              }, 500);
            }
          },
          "json"
        );
      });
    },
    api: {
      bindevent: function () {
        Form.api.bindevent($("form[role=form]"));
      },
    },
  };
  return Controller;
});
